package com.cgwx.tcservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgwx.servicebase.exceptionhandler.MyException;
import com.cgwx.tcservice.entity.tc.TcCommandConfig;
import com.cgwx.tcservice.entity.vo.TcCommandExcelVo;
import com.cgwx.tcservice.listener.TcCommandExcelListener;
import com.cgwx.tcservice.mapper.TcCommandConfigMapper;
import com.cgwx.tcservice.service.TcCommandConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 遥控指令配置表 服务实现类
 * </p>
 *
 * @author GaoWei
 * @since 2023-09-14
 */
@Service
public class TcCommandConfigServiceImpl extends ServiceImpl<TcCommandConfigMapper, TcCommandConfig> implements TcCommandConfigService {

//    更新遥控指令表配置
    @Override
    public Map<String,String> updateTcCommandConfig(MultipartFile file, TcCommandConfigService tcCommandConfigService) {
//        获取文件名称
        String uploadFileName = file.getOriginalFilename();
//        获取遥控指令帧名称（去掉.xls/.xlsx）
        String tcFrameName = Objects.requireNonNull(uploadFileName).substring(0,uploadFileName.indexOf('_') + 2);
//        从文件名称中提取关键字，部件代码_指令类型
        String tcFrameIdentifiers = tcFrameName.substring(tcFrameName.indexOf('_') - 2);

//        根据关键字查询是否存在同名遥控指令配置（同一遥控帧下的遥控指令）
        QueryWrapper<TcCommandConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tc_frame_identifiers",tcFrameIdentifiers);
        Integer queryCount = baseMapper.selectCount(queryWrapper);

        if(queryCount != 0){
//            如果有，删除此 遥控指令帧 下的所有 遥控指令 配置
            baseMapper.delete(queryWrapper);
        }

//        读取Excel中的数据，插入到表中
        try {
            InputStream inputStream = file.getInputStream();
//            调用方法读取，读取所有sheet，用doReadAll方法
            TcCommandExcelListener tcCommandExcelListener = new TcCommandExcelListener(tcCommandConfigService,tcFrameIdentifiers);
            EasyExcel.read(inputStream, TcCommandExcelVo.class, tcCommandExcelListener).doReadAll();
            return tcCommandExcelListener.getSheetNoToTcCommandCode();
        } catch (Exception e) {
            throw new MyException(20002,"读取遥控指令配置表格出错");
        }
    }
}
